package com.steven.realServer.service

import com.alibaba.fastjson.JSONObject
import com.steven.realServer.dao.IdentifyDao
import com.steven.realServer.dao.UserInfoDao
import com.steven.realServer.pojo.UserAllDetail
import com.steven.realServer.pojo.UserDetail
import com.steven.realServer.utils.FileTypeUtils
import com.steven.realServer.utils.NameUtils
import com.steven.realServer.utils.ResultUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.multipart.MultipartFile
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream
import java.util.*

@Service
open class IdentifyServiceImp : IdentifyService {
    @Autowired
    private val dao: IdentifyDao? = null

    @Autowired
    private val userInfoDao: UserInfoDao? = null
    override fun searchSchool(schoolName: String): JSONObject {
        val jsonObject = JSONObject()
        jsonObject["schoolList"] = dao!!.searchSchool(schoolName)
        return ResultUtils.makeResult(0, jsonObject)
    }

    override fun addUserDetail(detail: UserDetail): JSONObject {
        val jsonObject = JSONObject()
        val resultNum: Int = if (dao!!.searchUserDetail(detail.uid).size > 0) {
            dao.updateUserDetail(detail.uid, detail.uname, detail.school, detail.college, detail.judge, detail.schoolType, detail.startYear, detail.userType)
        } else {
            dao.addUserDetail(detail.uid, detail.uname, detail.school, detail.college, detail.judge, detail.schoolType, detail.startYear, detail.userType)
        }
        if (resultNum < 1) {
            jsonObject["msg"] = "提交失败"
        } else {
            jsonObject["msg"] = "success"
        }
        return ResultUtils.makeResult(0, jsonObject)
    }

    override fun queryUserIdentifyStatus(uid: Long): JSONObject {
        val jsonObject = JSONObject()
        val result = dao!!.searchUserDetail(uid)
        if (result.size < 1) {
            jsonObject["userType"] = ""
            jsonObject["status"] = -1
            jsonObject["msg"] = "success"
        } else {
            if(!result[0].uname.isNullOrEmpty()){
                if (result[0].status == 2) {
                    jsonObject["userType"] = result[0].userType
                } else {
                    jsonObject["userType"] = ""
                }
                jsonObject["status"] = result[0].status
            }else{
                jsonObject["userType"] = ""
                jsonObject["status"] = -1
            }
            jsonObject["msg"] = "success"
        }
        return ResultUtils.makeResult(0, jsonObject)
    }

    @Transactional
    override fun updateUserIdentify(uid: Long, normalUser: Long, canPass: Boolean): JSONObject? {
        val jsonObject = JSONObject()
        val status = queryUserIdentifyStatus(uid).getJSONObject("result").getString("userType")
        if (status == "admin") {
            try {
                val result = if (canPass) {
                    dao!!.updateUserIdentifyStatus(normalUser, 2)
                } else {
                    dao!!.updateUserIdentifyStatus(normalUser, 1)
                }
                if (result > 0)
                    jsonObject["msg"] = "success"
                else
                    jsonObject["msg"] = "用户状态已更新"
            } catch (e: Exception) {
                e.printStackTrace()
                jsonObject["msg"] = e.message
            }
        } else {
            jsonObject["msg"] = "用户缺少权限"
            return ResultUtils.makeResult(0, jsonObject)
        }
        return ResultUtils.makeResult(0, jsonObject)
    }

    override fun uploadStudent(image: MultipartFile?, uid: Long?): JSONObject {
        val jsonObject = JSONObject()
        if (uid == null) {
            jsonObject["msg"] = "请求异常(uid为空)"
            return ResultUtils.makeResult(0, jsonObject)
        }
        if (image == null) {
            jsonObject["msg"] = "图片不能为空"
            return ResultUtils.makeResult(0, jsonObject)
        }
        if (!testFileIsRight(image)) {
            jsonObject["msg"] = "文件类型错误"
            return ResultUtils.makeResult(0, jsonObject)
        }
        val imgName = uid.toString() + "_" + "identity" + "_" + Objects.requireNonNull(image.originalFilename).replace(" ".toRegex(), "")
        //val imgFilePath = "f:/pic/" + imgName;
        val imgFilePath = "/root/java/pic/$imgName"
        try {
            val out: OutputStream = FileOutputStream(imgFilePath)
            out.write(image.bytes)
            out.flush()
            out.close()
            if (dao!!.searchUserDetail(uid).size > 0) {
                dao.updateUserIdentityImage(uid, imgFilePath)
            } else {
                dao.addUserIdentityImage(uid, imgFilePath)
            }
            jsonObject["msg"] = "success"
        } catch (e: IOException) {
            jsonObject["msg"] = e.message
            e.printStackTrace()
        }
        return ResultUtils.makeResult(0, jsonObject)
    }

    private fun queryUserDetail(uid: Long?): UserAllDetail {
        val userAllDetail = UserAllDetail()
        val userInfo = userInfoDao!!.searchUserById(uid)
        if (userInfo.size > 0) {
            userAllDetail.userInfo = userInfo[0]
            val userDetailList = dao!!.searchUserDetail(uid)
            if (userDetailList.size > 0) {
                userAllDetail.userDetail = userDetailList[0]
            }
        }
        return userAllDetail
    }

    override fun queryUserName(uid: Long): JSONObject {
        val jsonObject = JSONObject()
        val userAllDetail = queryUserDetail(uid)
        val name = NameUtils.getUserName(userAllDetail)
        if (name != null) {
            jsonObject["msg"] = "success"
            jsonObject["name"] = name
        } else {
            jsonObject["msg"] = "请求异常"
        }
        return ResultUtils.makeResult(0, jsonObject)
    }

    override fun queryToBeConfirm(uid: Long): JSONObject? {
        val jsonObject = JSONObject()
        val status = queryUserIdentifyStatus(uid).getJSONObject("result").getString("userType")
        if (status == "admin") {
            jsonObject["data"] = dao!!.queryToBeConfirm()
            jsonObject["msg"] = "success"
        } else {
            jsonObject["msg"] = "用户缺少权限"
        }
        return ResultUtils.makeResult(0, jsonObject)
    }

    private fun testFileIsRight(file: MultipartFile): Boolean {
        return if (!file.isEmpty) {
            try {
                val type = FileTypeUtils.getFileTypeByStream(file.bytes)
                "jpg" == type || "png" == type
            } catch (e: IOException) {
                e.printStackTrace()
                false
            }
        } else {
            false
        }
    }
}